// ==UserScript==
// @name	OneDay
// @version	1
// @description	One Day Work
// @include	http://*.erepublik.com/en/*
// @include	http://erepublik.com/en/*
// @exclude	http://ads*.erepublik.com/*
// @require	http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// @require	http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js
// ==/UserScript==

var version = '1';
var pagesFunctions = [];
var BASE_URL = 'http://www.erepublik.com';
var LANG = 'en';

window.addEventListener('load', function(){var checker=setInterval(function(){
	if(typeof ($ = jQuery.noConflict()) != "undefined") {
		clearInterval(checker);
		Main();
	}
},100);}, false);

function Main(e) {
//	readSettings();

	var HREF = location.href;
	if (HREF.indexOf("http://")==0 || HREF.indexOf("https://")==0) {
		var parts = HREF.split('/');
		BASE_URL = parts[0]+'//'+parts[2];
		LANG = parts[3];
	}
	
	if (HREF.indexOf(BASE_URL+'/')==0) {
		LOCATION = HREF.substring(BASE_URL.length+4);
		pagesFunctions.forEach(function(v) {
			if ((v.p=="all" || LOCATION.indexOf(v.p)>=0)) {
				 v.f();
			}
		});
		
	}
	today = 1*$("#clock span.date").text().match(/[0-9]{2}/);
}
pagesFunctions.push({p: 'messages/alerts/',		c:'alert',	f: StartAlert});
var employees = {};
var companies = {};
var today;

function StartAlert() {
		today = 1*$("#clock span.date").text().match(/[0-9]{2}/);
		$("form.messages-form tr").each( function (i)  {
//			if ($(this).html().indexOf("applied")>0 && $(this).html().indexOf('-bell_notifications.gif')>0) { 
			if ($(this).html().indexOf("applied")>0) { 
				var cID = $(this).find('a:first').attr('href').split('/')[4];
				var compHREF = $(this).find('a:eq(1)').attr('href');
				var compID = compHREF.split('/')[3].split('-').pop();
				var name = cID+'-'+compID;
				employees['e'+name]='NA';
				companies['c'+compID]=compHREF;
				var id = 'fire-'+i+'-'+name;
				$(this).find('span.fakeheight').append('<br/><a class="firebutton" id="'+id+'" name="'+name+'">SEARCH</a>');
				$('#'+id).hide();
			}
		});
		
		for(var key in companies) {
			GM_xmlhttpRequest({
				method: "GET",
				url: BASE_URL+companies[key],
				onload: function(response) { 
					employees_url = $("#content div.holder.largepadded:first a:first",response.responseText).attr("href");
					nextEmployeePage(key.substr(1), employees_url);
				}
			});
		};
}

function nextEmployeePage(company, url) {
	GM_log('next:'+BASE_URL+url);
	GM_xmlhttpRequest({
		method: "GET",
		url: BASE_URL+url,
		onload: function(response) {
			GM_log('next onload:'+BASE_URL+url);
			var thisComp = $('#company_id',response.responseText).attr('value');
			date_runner_position = today - $("#date_runner p:first",response.responseText).text().match(/[0-9]{2}/);
			if(date_runner_position < 0) date_runner_position = 6 + today - $("#date_runner p:first",data).text().match(/0[0-9]/);
			$("table.employees_details tbody tr",response.responseText).each(function(i) {
				var worked = false;
				try {
					var productivity = 1*$.trim($("td.e_productivity li p",this).eq(date_runner_position).text());
					worked = productivity>0;
				} catch (c) {
				}
				try {
					var fireCode = $("td.e_salary a.i_edit",this).attr('id');
					var cID = $("div.avatarholder a",this).attr('href').split('/').pop();
					var name = cID+'-'+thisComp;
					if (employees['e'+name]=='NA') {
						employees['e'+name] = fireCode;
						$('a.firebutton').each( function (i) {
							if ($(this).attr('name')==name) {
								$(this).html('Fire '+(worked?'worked':'busy'));
								$(this).show();
								$(this).click(function () {
									var name = this.name;
									var companyID = name.split('-')[1];
									var fireCode = employees['e'+name];
									if (!fireCode || fireCode=='NA') {
										alert('Employee NOT found');
									} else {
										var url = BASE_URL+'/en/fire-employee/company-'+companyID+'-employee-'+fireCode;
										GM_log('this:'+name+"||"+url);
										var button = this;
										GM_xmlhttpRequest({
											method: "GET",
											url: url,
											onload: function(response) { 
												employees['e'+name]=null;
												$(button).html('Fired');
												$(button).attr("disabled","disabled");
											}, 
											onerror: function(response) {
												GM_log('err:'+response.status);
											}
										});
									}
									return false;
								});
							}
						});
					}
				} catch(e) {
					GM_log('err:'+e+','+thisComp+','+$(this).html());
				}
			});
			if ($('ul.pager a.last',response.responseText).size()>0) {
				var urlParts = url.split('/');
				nextEmployeePage(thisComp, '/'+urlParts[1]+'/'+urlParts[2]+'/'+urlParts[3]+'/'+urlParts[4]+'/'+(urlParts[5]*1+1));
			}
		}
	});
}
